package com.storage.framework.shiro.realm;

import com.storage.framework.jwt.GlobalError;
import com.storage.framework.jwt.JwtToken;
import com.storage.framework.util.JwtUtil;
import com.storage.system.domain.StorageUser;
import com.storage.system.mapper.StorageUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lixiao
 * @date 2019/8/6 10:02
 */
public class JwtRealm extends AuthorizingRealm {

    @Resource
    private StorageUserMapper storageUserMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("admin");
        info.addStringPermission("*:*:*");
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得token
        String phone = JwtUtil.getPhone(token);
        StorageUser user = storageUserMapper.selectUserByPhoneNumber(phone);
        // 进行有效期验证
        if (!JwtUtil.verify(token, user.getPassword())) {
            if (!Objects.equals(JwtUtil.getSecret(token), user.getPassword())) {
                throw new IncorrectCredentialsException(GlobalError.PASSWORD_HAS_CHANGED.getErrMsg());
            } else {
                throw new IncorrectCredentialsException(GlobalError.TOKEN_HAS_EXPIRED.getErrMsg());
            }
        }
        return new SimpleAuthenticationInfo(token, token, "JwtRealm");
    }
}
